<?php

namespace addons\yunfood\library;


use app\admin\model\yunfood\Shop as ShopModel;
use addons\yunfood\model\Config;
use think\Cache;

/**
 * 自定义后台
 */
class Backend extends \app\common\controller\Backend
{
    /**
     */
    protected $shopId = 0;

    protected $shopField;

    protected $superAdmin = false;

    public function _initialize()
    {
        parent::_initialize();

        // 门店管理员关联shopIds
        if ($this->auth->isSuperAdmin()) {
            $this->superAdmin = true;
        } else {
            $adminRoleId = Config::getGroupAttribute(Config::GROUP_BASE, 'admin_role');
            if ($adminRoleId && in_array($adminRoleId, $this->auth->getGroupIds())) {
                $this->superAdmin = true;
            }
        }
        if (! $this->superAdmin) {
            $this->shopId = Cache::remember('shopIds:' . $this->auth->id, function () {
                $shop = ShopModel::field(['id'])->show()
                    ->where('find_in_set(:aid, `admin_ids`)', ['aid' => $this->auth->id])->find();

                return $shop->id ?? 0;
            }, 300);
        }
    }

    /**
     * @param null|callable $where
     * @param string $field
     * @return array|\Closure|mixed|null
     */
    protected function getShopWhere($where = null, $field = 'shop_id')
    {
        if (! $this->superAdmin && $this->shopId) {
            $where = function ($query) use ($field, $where) {
                $query->where($field . ' = \'\' or find_in_set(' . $this->shopId . ', ' . $field . ')');
                if ($where) {
                    $where($query);
                }
            };
        }

        return $where;
    }

    protected function authToShop($shopId)
    {
        if (! $this->superAdmin && $this->shopId) {
            if (is_array($shopId)) {
                if (count($shopId) > 1) {
                    $this->error('没有操作权限');
                }
                $shopId = $shopId[0];
            }
            if ($shopId != $this->shopId) {
                $this->error('没有操作权限');
            }
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        $params = $this->request->post("row/a");
        if ($params) {
            $params = $this->preExcludeFields($params);
            if ($this->shopField) {
                $this->authToShop($params[$this->shopField] ?? null);
            }
        }

        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if ($row) {
            if ($this->shopField) {
                $this->authToShop($row[$this->shopField]);
            }
        }

        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $ids = $ids ?: $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            foreach ($list as $item) {
                if ($this->shopField) {
                    $this->authToShop($item[$this->shopField]);
                }
            }
        }
        parent::del();
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ?: $this->request->post('ids');
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post('params'), $values);
                $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values,
                    array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                    foreach ($list as $item) {
                        if ($this->shopField) {
                            $this->authToShop($item[$this->shopField]);
                        }
                    }
                }
            }
        }
        parent::multi();
    }
}
